DonorsChoose.org receives hundreds of thousands of project proposals each year for classroom projects in need of funding. Right now, a large number of volunteers is needed to manually screen each submission before it's approved to be posted on the DonorsChoose.org website.
Next year, DonorsChoose.org expects to receive close to 500,000 project proposals. As a result, there are three main problems they need to solve:
The goal of the competition is to predict whether or not a DonorsChoose.org project proposal submitted by a teacher will be approved, using the text of project descriptions as well as additional metadata about the project, teacher, and school. DonorsChoose.org can then use this information to identify projects most likely to need further review before approval.
The train.csv data set provided by DonorsChoose contains the following features:
| Feature | Description |
|---|---|
project_id |
A unique identifier for the proposed project. Example: p036502 |
project_title |
Title of the project. Examples:
|
project_grade_category |
Grade level of students for which the project is targeted. One of the following enumerated values:
|
project_subject_categories |
One or more (comma-separated) subject categories for the project from the following enumerated list of values:
Examples:
|
school_state |
State where school is located (Two-letter U.S. postal code). Example: WY |
project_subject_subcategories |
One or more (comma-separated) subject subcategories for the project. Examples:
|
project_resource_summary |
An explanation of the resources needed for the project. Example:
|
project_essay_1 |
First application essay* |
project_essay_2 |
Second application essay* |
project_essay_3 |
Third application essay* |
project_essay_4 |
Fourth application essay* |
project_submitted_datetime |
Datetime when project application was submitted. Example: 2016-04-28 12:43:56.245 |
teacher_id |
A unique identifier for the teacher of the proposed project. Example: bdf8baa8fedef6bfeec7ae4ff1c15c56 |
teacher_prefix |
Teacher's title. One of the following enumerated values:
|
teacher_number_of_previously_posted_projects |
Number of project applications previously submitted by the same teacher. Example: 2 |
* See the section Notes on the Essay Data for more details about these features.
Additionally, the resources.csv data set provides more data about the resources required for each project. Each line in this file represents a resource required by a project:
| Feature | Description |
|---|---|
id |
A project_id value from the train.csv file. Example: p036502 |
description |
Desciption of the resource. Example: Tenor Saxophone Reeds, Box of 25 |
quantity |
Quantity of the resource required. Example: 3 |
price |
Price of the resource required. Example: 9.95 |
Note: Many projects require multiple resources. The id value corresponds to a project_id in train.csv, so you use it as a key to retrieve all resources needed for a project:
The data set contains the following label (the value you will attempt to predict):
| Label | Description |
|---|---|
project_is_approved |
A binary flag indicating whether DonorsChoose approved the project. A value of 0 indicates the project was not approved, and a value of 1 indicates the project was approved. |
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
import sqlite3
import pandas as pd
import numpy as np
import nltk
import string
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import confusion_matrix
from sklearn import metrics
from sklearn.metrics import roc_curve, auc
from nltk.stem.porter import PorterStemmer
import re
# Tutorial about Python regular expressions: https://pymotw.com/2/re/
import string
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer
from gensim.models import Word2Vec
from gensim.models import KeyedVectors
import pickle
from tqdm import tqdm
import os
#from plotly import plotly
import plotly.offline as offline
import plotly.graph_objs as go
offline.init_notebook_mode()
from collections import Counter
project_data = pd.read_csv('train_data.csv')
resource_data = pd.read_csv('resources.csv')
print("Number of data points in train data", project_data.shape)
print('-'*50)
print("The attributes of data :", project_data.columns.values)
print("Number of data points in train data", resource_data.shape)
print(resource_data.columns.values)
resource_data.head(2)
project_subject_categories¶catogories = list(project_data['project_subject_categories'].values)
# remove special characters from list of strings python: https://stackoverflow.com/a/47301924/4084039
# https://www.geeksforgeeks.org/removing-stop-words-nltk-python/
# https://stackoverflow.com/questions/23669024/how-to-strip-a-specific-word-from-a-string
# https://stackoverflow.com/questions/8270092/remove-all-whitespace-in-a-string-in-python
cat_list = []
for i in catogories:
temp = ""
# consider we have text like this "Math & Science, Warmth, Care & Hunger"
for j in i.split(','): # it will split it in three parts ["Math & Science", "Warmth", "Care & Hunger"]
if 'The' in j.split(): # this will split each of the catogory based on space "Math & Science"=> "Math","&", "Science"
j=j.replace('The','') # if we have the words "The" we are going to replace it with ''(i.e removing 'The')
j = j.replace(' ','') # we are placeing all the ' '(space) with ''(empty) ex:"Math & Science"=>"Math&Science"
temp+=j.strip()+" " #" abc ".strip() will return "abc", remove the trailing spaces
temp = temp.replace('&','_') # we are replacing the & value into
cat_list.append(temp.strip())
project_data['clean_categories'] = cat_list
project_data.drop(['project_subject_categories'], axis=1, inplace=True)
from collections import Counter
my_counter = Counter()
for word in project_data['clean_categories'].values:
my_counter.update(word.split())
cat_dict = dict(my_counter)
sorted_cat_dict = dict(sorted(cat_dict.items(), key=lambda kv: kv[1]))
project_subject_subcategories¶sub_catogories = list(project_data['project_subject_subcategories'].values)
# remove special characters from list of strings python: https://stackoverflow.com/a/47301924/4084039
# https://www.geeksforgeeks.org/removing-stop-words-nltk-python/
# https://stackoverflow.com/questions/23669024/how-to-strip-a-specific-word-from-a-string
# https://stackoverflow.com/questions/8270092/remove-all-whitespace-in-a-string-in-python
sub_cat_list = []
for i in sub_catogories:
temp = ""
# consider we have text like this "Math & Science, Warmth, Care & Hunger"
for j in i.split(','): # it will split it in three parts ["Math & Science", "Warmth", "Care & Hunger"]
if 'The' in j.split(): # this will split each of the catogory based on space "Math & Science"=> "Math","&", "Science"
j=j.replace('The','') # if we have the words "The" we are going to replace it with ''(i.e removing 'The')
j = j.replace(' ','') # we are placeing all the ' '(space) with ''(empty) ex:"Math & Science"=>"Math&Science"
temp +=j.strip()+" "#" abc ".strip() will return "abc", remove the trailing spaces
temp = temp.replace('&','_')
sub_cat_list.append(temp.strip())
project_data['clean_subcategories'] = sub_cat_list
project_data.drop(['project_subject_subcategories'], axis=1, inplace=True)
# count of all the words in corpus python: https://stackoverflow.com/a/22898595/4084039
my_counter = Counter()
for word in project_data['clean_subcategories'].values:
my_counter.update(word.split())
sub_cat_dict = dict(my_counter)
sorted_sub_cat_dict = dict(sorted(sub_cat_dict.items(), key=lambda kv: kv[1]))
teacher_pre = []
for prefix in project_data['teacher_prefix'].values:
if prefix==prefix:
prefix = re.sub('[^A-Za-z0-9]','',prefix).lower()
teacher_pre.append(prefix)
else:
teacher_pre.append(prefix)
project_data['teacher_prefix'] = teacher_pre
project_grade_cat = []
for grade in project_data['project_grade_category'].values:
grade = grade.replace('-','_').lower()
grade = grade.replace(' ','_').lower()
project_grade_cat.append(grade)
project_data['project_grade_category'] = project_grade_cat
# merge two column text dataframe:
project_data["essay"] = project_data["project_essay_1"].map(str) +\
project_data["project_essay_2"].map(str) + \
project_data["project_essay_3"].map(str) + \
project_data["project_essay_4"].map(str)
project_data.head(2)
#### 1.4.2.3 Using Pretrained Models: TFIDF weighted W2V
# printing some random reviews
print(project_data['essay'].values[0])
print("="*50)
print(project_data['essay'].values[150])
print("="*50)
print(project_data['essay'].values[1000])
print("="*50)
print(project_data['essay'].values[20000])
print("="*50)
print(project_data['essay'].values[99999])
print("="*50)
# https://stackoverflow.com/a/47091490/4084039
import re
def decontracted(phrase):
# specific
phrase = re.sub(r"won't", "will not", phrase)
phrase = re.sub(r"can\'t", "can not", phrase)
# general
phrase = re.sub(r"n\'t", " not", phrase)
phrase = re.sub(r"\'re", " are", phrase)
phrase = re.sub(r"\'s", " is", phrase)
phrase = re.sub(r"\'d", " would", phrase)
phrase = re.sub(r"\'ll", " will", phrase)
phrase = re.sub(r"\'t", " not", phrase)
phrase = re.sub(r"\'ve", " have", phrase)
phrase = re.sub(r"\'m", " am", phrase)
return phrase
sent = decontracted(project_data['essay'].values[20000])
print(sent)
print("="*50)
# \r \n \t remove from string python: http://texthandler.com/info/remove-line-breaks-python/
sent = sent.replace('\\r', ' ')
sent = sent.replace('\\"', ' ')
sent = sent.replace('\\n', ' ')
print(sent)
#remove spacial character: https://stackoverflow.com/a/5843547/4084039
sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
print(sent)
# https://gist.github.com/sebleier/554280
# we are removing the words from the stop words list: 'no', 'nor', 'not'
stopwords= ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've",\
"you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', \
'she', "she's", 'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their',\
'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', \
'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', \
'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', \
'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after',\
'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further',\
'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more',\
'most', 'other', 'some', 'such', 'only', 'own', 'same', 'so', 'than', 'too', 'very', \
's', 't', 'can', 'will', 'just', 'don', "don't", 'should', "should've", 'now', 'd', 'll', 'm', 'o', 're', \
've', 'y', 'ain', 'aren', "aren't", 'couldn', "couldn't", 'didn', "didn't", 'doesn', "doesn't", 'hadn',\
"hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't", 'ma', 'mightn', "mightn't", 'mustn',\
"mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn', "shouldn't", 'wasn', "wasn't", 'weren', "weren't", \
'won', "won't", 'wouldn', "wouldn't"]
from sklearn.model_selection import train_test_split as tts
X_train,X_test,y_train,y_test = tts(project_data,project_data['project_is_approved'],test_size = 0.2, stratify = project_data['project_is_approved'])
X_train.drop(['project_is_approved'],axis=1,inplace=True)
X_test.drop(['project_is_approved'],axis=1,inplace=True)
#X_cv.drop(['project_is_approved'],axis=1,inplace=True)
print(X_train.shape)
print(X_test.shape)
X_train = pd.read_csv('X_train')
X_test = pd.read_csv('X_test')
y_train = pd.read_csv('Y_train',names = ['Unnamed:0','project_is_approved'])
y_test = pd.read_csv('Y_test',names = ['Unnamed:0','project_is_approved'])
project_grade_cat_train = []
for grade in X_train['project_grade_category'].values:
grade = grade.replace('-','_').lower()
grade = grade.replace(' ','_').lower()
project_grade_cat_train.append(grade)
X_train['project_grade_category'] = project_grade_cat_train
project_grade_cat_test = []
for grade in X_test['project_grade_category'].values:
grade = grade.replace('-','_').lower()
grade = grade.replace(' ','_').lower()
project_grade_cat_test.append(grade)
X_test['project_grade_category'] = project_grade_cat_test
# Combining all the above stundents
from tqdm import tqdm
preprocessed_essays_train = []
# tqdm is for printing the status bar
for sentance in tqdm(X_train['essay'].values):
sent = decontracted(sentance)
sent = sent.replace('\\r', ' ')
sent = sent.replace('\\"', ' ')
sent = sent.replace('\\n', ' ')
sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
# https://gist.github.com/sebleier/554280
sent = ' '.join(e for e in sent.split() if e.lower() not in stopwords)
preprocessed_essays_train.append(sent.lower().strip())
preprocessed_essays_test = []
# tqdm is for printing the status bar
for sentance in tqdm(X_test['essay'].values):
sent = decontracted(sentance)
sent = sent.replace('\\r', ' ')
sent = sent.replace('\\"', ' ')
sent = sent.replace('\\n', ' ')
sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
# https://gist.github.com/sebleier/554280
sent = ' '.join(e for e in sent.split() if e.lower() not in stopwords)
preprocessed_essays_test.append(sent.lower().strip())
# similarly you can preprocess the titles also
preprocessed_titles_train =[]
for title in tqdm(X_train['project_title'].values):
des = decontracted(title)
des = des.replace("\\r",' ')
des = des.replace('\\"',' ')
des = des.replace('\\n',' ')
des = re.sub('[^A-Za-z0-9]+',' ',des)
des = ' '.join(e for e in des.split() if e.lower() not in stopwords)
preprocessed_titles_train.append(des.lower().strip())
preprocessed_titles_test =[]
for title in tqdm(X_test['project_title'].values):
des = decontracted(title)
des = des.replace("\\r",' ')
des = des.replace('\\"',' ')
des = des.replace('\\n',' ')
des = re.sub('[^A-Za-z0-9]+',' ',des)
des = ' '.join(e for e in des.split() if e.lower() not in stopwords)
preprocessed_titles_test.append(des.lower().strip())
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
senti = SentimentIntensityAnalyzer()
positive_tr,positive_ts,positive_cv=[],[],[]
negative_tr ,negative_ts,negative_cv= [],[],[]
neutral_tr,neutral_ts,neutral_cv = [],[],[]
comp_tr ,comp_ts,comp_cv= [],[],[]
for i in tqdm(X_train['essay']):
positive_tr.append(senti.polarity_scores(i)['pos'])
negative_tr.append(senti.polarity_scores(i)['neg'])
neutral_tr.append(senti.polarity_scores(i)['neu'])
comp_tr.append(senti.polarity_scores(i)['compound'])
X_train['pos'] = positive_tr
X_train['neg'] = negative_tr
X_train['neu'] = neutral_tr
X_train['comp'] = comp_tr
for i in tqdm(X_test['essay']):
positive_ts.append(senti.polarity_scores(i)['pos'])
negative_ts.append(senti.polarity_scores(i)['neg'])
neutral_ts.append(senti.polarity_scores(i)['neu'])
comp_ts.append(senti.polarity_scores(i)['compound'])
X_test['pos'] = positive_ts
X_test['neg'] = negative_ts
X_test['neu'] = neutral_ts
X_test['comp'] = comp_ts
project_data.columns
we are going to consider
- school_state : categorical data
- clean_categories : categorical data
- clean_subcategories : categorical data
- project_grade_category : categorical data
- teacher_prefix : categorical data
- project_title : text data
- text : text data
- project_resource_summary: text data (optinal)
- quantity : numerical (optinal)
- teacher_number_of_previously_posted_projects : numerical
- price : numerical
# we use count vectorizer to convert the values into one
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer( lowercase=False, binary=True)
vectorizer.fit(X_train['clean_categories'].values)
categories_one_hot_train = vectorizer.transform(preprocessed_essays_train)
categories_one_hot_test = vectorizer.transform(preprocessed_essays_test)
#categories_one_hot_cv = vectorizer.transform(preprocessed_essays_cv)
print(vectorizer.get_feature_names())
print("Shape of Train matrix after one hot encodig ",categories_one_hot_train.shape)
print("Shape of Test matrix after one hot encodig ",categories_one_hot_test.shape)
#print("Shape of CV matrix after one hot encodig ",categories_one_hot_cv.shape)
# we use count vectorizer_sub to convert the values into one
from sklearn.feature_extraction.text import CountVectorizer
vectorizer_sub = CountVectorizer( lowercase=False, binary=True)
vectorizer_sub.fit(X_train['clean_subcategories'].values)
sub_categories_one_hot_train = vectorizer_sub.transform(preprocessed_titles_train)
sub_categories_one_hot_test = vectorizer_sub.transform(preprocessed_titles_test)
#sub_categories_one_hot_cv = vectorizer_sub.transform(preprocessed_titles_cv)
print(vectorizer_sub.get_feature_names())
print("Shape of Train matrix after one hot encodig ",sub_categories_one_hot_train.shape)
print("Shape of Test matrix after one hot encodig ",sub_categories_one_hot_test.shape)
#print("Shape of CV matrix after one hot encodig ",sub_categories_one_hot_cv.shape)
#https://stackoverflow.com/questions/11620914/removing-nan-values-from-an-array
#https://stackoverflow.com/questions/39303912/tfidfvectorizer-in-scikit-learn-valueerror-np-nan-is-an-invalid-document
vectorizer_prefix = CountVectorizer(lowercase = False,binary = True)
vectorizer_prefix = vectorizer_prefix.fit(X_train['teacher_prefix'].values.astype('U'))
prefix_one_hot_train = vectorizer_prefix.transform(X_train['teacher_prefix'].values.astype('U'))
#prefix_one_hot_cv = vectorizer.transform(X_cv['teacher_prefix'].values.astype('U'))
prefix_one_hot_test = vectorizer_prefix.transform(X_test['teacher_prefix'].values.astype('U'))
print(vectorizer_prefix.get_feature_names())
print("Shape of matrix after one hot encoding ", prefix_one_hot_train.shape)
#print("Shape of matrix after one hot encoding ", prefix_one_hot_cv.shape)
print("Shape of matrix after one hot encoding ", prefix_one_hot_test.shape)
vectorizer_grade = CountVectorizer(lowercase = False,binary = True)
vectorizer_grade = vectorizer_grade.fit(X_train['project_grade_category'].values.astype('U'))
project_grade_one_hot_train = vectorizer_grade.transform(X_train['project_grade_category'].values.astype('U'))
#project_grade_one_hot_cv = vectorizer.transform(X_cv['project_grade_category'].values.astype('U'))
project_grade_one_hot_test = vectorizer_grade.transform(X_test['project_grade_category'].values.astype('U'))
print(vectorizer_grade.get_feature_names())
print("Shape of matrix after one hot encoding ", project_grade_one_hot_train.shape)
#print("Shape of matrix after one hot encoding ", project_grade_one_hot_cv.shape)
print("Shape of matrix after one hot encoding ", project_grade_one_hot_test.shape)
vectorizer_state = CountVectorizer(lowercase = False,binary = True)
vectorizer_state.fit(X_train['school_state'].values)
state_one_hot_train = vectorizer_state.transform(X_train['school_state'].values)
state_one_hot_test = vectorizer_state.transform(X_test['school_state'].values)
#state_one_hot_cv = vectorizer.transform(X_cv['school_state'].values)
print(vectorizer_state.get_feature_names())
print("Shape of Train matrix after one hot encoding ", state_one_hot_train.shape)
print("Shape of Test matrix after one hot encoding ", state_one_hot_test.shape)
#print("Shape of cv matrix after one hot encoding ", state_one_hot_cv.shape)
essay_word_counter_train = []
title_word_counter_train = []
for sent in preprocessed_essays_train:
count = len(set(sent.split()))
essay_word_counter_train.append(count)
for title in preprocessed_titles_train:
count = len(set(title.split()))
title_word_counter_train.append(count)
X_train['Essay_word_count'] = essay_word_counter_train
X_train['Title_word_count'] = title_word_counter_train
essay_word_counter_test = []
title_word_counter_test = []
for sent in preprocessed_essays_test:
count = len(set(sent.split()))
essay_word_counter_test.append(count)
for title in preprocessed_titles_test:
count = len(set(title.split()))
title_word_counter_test.append(count)
X_test['Essay_word_count'] = essay_word_counter_test
X_test['Title_word_count'] = title_word_counter_test
price_data = resource_data.groupby('id').agg({'price':'sum', 'quantity':'sum'}).reset_index()
X_train = pd.merge(X_train, price_data, on='id', how='left')
#X_cv = pd.merge(X_cv,price_data, on ='id',how = 'left')
X_test = pd.merge(X_test,price_data, on ='id',how = 'left')
# check this one: https://www.youtube.com/watch?v=0HOqOcln3Z4&t=530s
# standardization sklearn: https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html
from sklearn.preprocessing import StandardScaler,Normalizer
# price_standardized = standardScalar.fit(project_data['price'].values)
# this will rise the error
# ValueError: Expected 2D array, got 1D array instead: array=[725.05 213.03 329. ... 399. 287.73 5.5 ].
# Reshape your data either using array.reshape(-1, 1)
price_scalar = Normalizer()
price_scalar.fit(X_train['price'].values.reshape(1,-1)) # finding the mean and standard deviation of this data
#print(f"Mean : {price_scalar.mean_[0]}, Standard deviation : {np.sqrt(price_scalar.var_[0])}")
# Now standardize the data with above maen and variance.
price_standardized_train = price_scalar.transform(X_train['price'].values.reshape(1, -1)).reshape(-1,1)
#price_standardized_cv = price_scalar.transform(X_cv['price'][0:12000].values.reshape(-1,1))
price_standardized_test = price_scalar.transform(X_test['price'].values.reshape(1,-1)).reshape(-1,1)
# standardized quantity columns
quantity_scaler = Normalizer()
quantity_scaler.fit(X_train['quantity'].values.reshape(1,-1))
#print(f"Mean :{quantity_scaler.mean_[0]},Standard Deviation :{np.sqrt(quantity_scaler.var_[0])}")
quantity_standardized_train = quantity_scaler.transform(X_train['quantity'].values.reshape(1,-1)).reshape(-1,1)
#quantity_standardized_cv = quantity_scaler.transform(X_cv['quantity'][0:12000].values.reshape(-1,1))
quantity_standardized_test = quantity_scaler.transform(X_test['quantity'].values.reshape(1,-1)).reshape(-1,1)
#standardized projects proposed by teachers
project_scaler = Normalizer()
project_scaler.fit(X_train['teacher_number_of_previously_posted_projects'].values.reshape(1,-1))
#print(f"Mean :{project_scaler.mean_[0]},Standard Deviation :{np.sqrt(project_scaler.var_[0])}")
project_standardized_train = project_scaler.transform(X_train['teacher_number_of_previously_posted_projects'].values.reshape(1,-1)).reshape(-1,1)
#project_standardized_cv = project_scaler.transform(X_cv['teacher_number_of_previously_posted_projects'][0:12000].values.reshape(-1,1))
project_standardized_test = project_scaler.transform(X_test['teacher_number_of_previously_posted_projects'].values.reshape(1,-1)).reshape(-1,1)
#standardized Essay Count
Essay_count_scaler = Normalizer()
Essay_count_scaler.fit(X_train['Essay_word_count'].values.reshape(1,-1))
#print(f"Mean :{Essay_count_scaler.mean_[0]},Standard Deviation :{np.sqrt(Essay_count_scaler.var_[0])}")
Essay_count_standardized_train = Essay_count_scaler.transform(X_train['Essay_word_count'].values.reshape(1,-1)).reshape(-1,1)
Essay_count_standardized_test = Essay_count_scaler.transform(X_test['Essay_word_count'].values.reshape(1,-1)).reshape(-1,1)
#Essay_count_standardized_cv = Essay_count_scaler.transform(X_cv['Essay_word_count'][:45000].values.reshape(-1,1))
#standardized Title Count
title_count_scaler = Normalizer()
title_count_scaler.fit(X_train['Title_word_count'].values.reshape(1,-1))
#print(f"Mean :{title_count_scaler.mean_[0]},Standard Deviation :{np.sqrt(title_count_scaler.var_[0])}")
title_count_standardized_train = title_count_scaler.transform(X_train['Title_word_count'].values.reshape(1,-1)).reshape(-1,1)
title_count_standardized_test = title_count_scaler.transform(X_test['Title_word_count'].values.reshape(1,-1)).reshape(-1,1)
#title_count_standardized_cv = title_count_scaler.transform(X_cv['Title_word_count'][:45000].values.reshape(-1,1))
# normalize positive sentiment of essay
pos_senti_scaler = Normalizer()
pos_senti_scaler.fit(X_train['pos'].values.reshape(1,-1))
essay_pos_train = pos_senti_scaler.transform(X_train['pos'].values.reshape(1,-1)).reshape(-1,1)
essay_pos_test = pos_senti_scaler.transform(X_test['pos'].values.reshape(1,-1)).reshape(-1,1)
neg_senti_scaler = Normalizer()
neg_senti_scaler.fit(X_train['neg'].values.reshape(1,-1))
essay_neg_train = neg_senti_scaler.transform(X_train['neg'].values.reshape(1,-1)).reshape(-1,1)
essay_neg_test = neg_senti_scaler.transform(X_test['neg'].values.reshape(1,-1)).reshape(-1,1)
neu_senti_scaler = Normalizer()
neu_senti_scaler.fit(X_train['neu'].values.reshape(1,-1))
essay_neu_train = neu_senti_scaler.transform(X_train['neu'].values.reshape(1,-1)).reshape(-1,1)
essay_neu_test = neu_senti_scaler.transform(X_test['neu'].values.reshape(1,-1)).reshape(-1,1)
comp_senti_scaler = Normalizer()
comp_senti_scaler.fit(X_train['comp'].values.reshape(1,-1))
essay_comp_train = comp_senti_scaler.transform(X_train['comp'].values.reshape(1,-1)).reshape(-1,1)
essay_comp_test = comp_senti_scaler.transform(X_test['comp'].values.reshape(1,-1)).reshape(-1,1)
n_components) using elbow method
- The shape of the matrix after TruncatedSVD will be 2000*n, i.e. each row represents a vector form of the corresponding word.
- Vectorize the essay text and project titles using these word vectors. (while vectorizing, do ignore all the words which are not in top 2k words)
import sys
import math
import numpy as np
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import roc_auc_score
# you might need to install this one
import xgboost as xgb
class XGBoostClassifier():
def __init__(self, num_boost_round=10, **params):
self.clf = None
self.num_boost_round = num_boost_round
self.params = params
self.params.update({'objective': 'multi:softprob'})
def fit(self, X, y, num_boost_round=None):
num_boost_round = num_boost_round or self.num_boost_round
self.label2num = {label: i for i, label in enumerate(sorted(set(y)))}
dtrain = xgb.DMatrix(X, label=[self.label2num[label] for label in y])
self.clf = xgb.train(params=self.params, dtrain=dtrain, num_boost_round=num_boost_round, verbose_eval=1)
def predict(self, X):
num2label = {i: label for label, i in self.label2num.items()}
Y = self.predict_proba(X)
y = np.argmax(Y, axis=1)
return np.array([num2label[i] for i in y])
def predict_proba(self, X):
dtest = xgb.DMatrix(X)
return self.clf.predict(dtest)
def score(self, X, y):
Y = self.predict_proba(X)[:,1]
return roc_auc_score(y, Y)
def get_params(self, deep=True):
return self.params
def set_params(self, **params):
if 'num_boost_round' in params:
self.num_boost_round = params.pop('num_boost_round')
if 'objective' in params:
del params['objective']
self.params.update(params)
return self
'''clf = XGBoostClassifier(eval_metric = 'auc', num_class = 2, nthread = 4,)
###################################################################
# Change from here #
###################################################################
parameters = {
'num_boost_round': [100, 250, 500],
'eta': [0.05, 0.1, 0.3],
'max_depth': [6, 9, 12],
'subsample': [0.9, 1.0],
'colsample_bytree': [0.9, 1.0],
}
clf = GridSearchCV(clf, parameters)
X = np.array([[1,2], [3,4], [2,1], [4,3], [1,0], [4,5]])
Y = np.array([0, 1, 0, 1, 0, 1])
clf.fit(X, Y)
# print(clf.grid_scores_)
best_parameters, score, _ = max(clf.grid_scores_, key=lambda x: x[1])
print('score:', score)
for param_name in sorted(best_parameters.keys()):
print("%s: %r" % (param_name, best_parameters[param_name]))
'''
from sklearn.feature_extraction.text import TfidfVectorizer
total_text = []
for i in range(80000):
total_text.append(preprocessed_essays_train[i] + preprocessed_titles_train[i])
vectorizer = TfidfVectorizer(min_df = 10,use_idf = True,stop_words=stopwords)
model_2000 = vectorizer.fit_transform(total_text)
top_2000 = pd.DataFrame({"feature_names":list(vectorizer.get_feature_names()),"idf_values":list(vectorizer.idf_)})
top_2000_features = top_2000.sort_values(by=['idf_values'],ascending=False)[:2000]
top_2000_features[:10]
def get_co_occur_matrix(data, vocab, context_window=2):
a = pd.DataFrame(np.zeros((len(vocab), len(vocab))), index=vocab, columns=vocab)
for review in data:
words = review.split()
for idx in tqdm(range(len(words))):
if a.get(words[idx]) is None:
continue
for i in tqdm(range(1, context_window+1)):
if idx-i >= 0:
if a.get(words[idx-i]) is not None:
a[words[idx-i]].loc[words[idx]] = a.get(words[idx-i]).loc[words[idx]] + 1
a[words[idx]].loc[words[idx-i]] = a.get(words[idx]).loc[words[idx-i]] + 1
if idx+i < len(words):
if a.get(words[idx+i]) is not None:
a[words[idx+i]].loc[words[idx]] = a.get(words[idx+i]).loc[words[idx]] + 1
a[words[idx]].loc[words[idx+i]] = a.get(words[idx]).loc[words[idx+i]] + 1
np.fill_diagonal(a.values, 0)
return a
co_matrix = get_co_occur_matrix(total_text, list(top_2000_features['feature_names'].values))
get_co_occur_matrix(["abc def ijk pqr",
"pqr klm opq",
"lmn pqr xyz abc def pqr abc"],["abc", "pqr", "def"],context_window=2)/2
co_matrix.to_csv("Co_Occurence")
co_matrix.describe()
co_matrix = pd.read_csv("Co_Occurence")
co_matrix = co_matrix.set_index("Unnamed: 0")/2
from sklearn.decomposition import TruncatedSVD
model = TruncatedSVD(n_components=1999,random_state=42)
model_svd=model.fit_transform(co_matrix)
variance = list(np.cumsum(model.explained_variance_ratio_))
index = list(np.arange(1,2000,1))
fig = go.Figure()
fig.add_trace(go.Scatter(x = index,y = variance,name = "Variance Explained"))
fig.add_trace(go.Scatter(x = [737],y=[1],marker = dict(color = 'red'),name = "First Point with Variance 1"))
fig.update_layout(title_text = "N_Components vs Explained Variance Ratio",xaxis = dict(title = "n_components")
,yaxis = dict(title = "Variance"))
from sklearn.decomposition import TruncatedSVD
model = TruncatedSVD(n_components=737,random_state=42)
model_svd = model.fit_transform(co_matrix)
model_svd.shape
model_svd[0]
top_feats = list(top_2000_features.feature_names.values)
indx = 0
essay_vectorizer_train = []
for text in tqdm(preprocessed_essays_train[:45000]):
vect_sum = np.zeros((1,737))
count = 0
for word in tqdm(text.split()):
if word in top_feats:
indx = top_feats.index(word)
count+=1
vect_sum+=model_svd[indx]
if count!=0:
vect_sum = vect_sum/count
else:
vect_sum = vect_sum
essay_vectorizer_train.append(vect_sum)
top_feats = list(top_2000_features.feature_names.values)
indx = 0
essay_vectorizer_test = []
for text in tqdm(preprocessed_essays_test[:15000]):
vect_sum = np.zeros((1,737))
count = 0
for word in tqdm(text.split()):
if word in top_feats:
indx = top_feats.index(word)
count+=1
vect_sum+=model_svd[indx]
if count!=0:
vect_sum = vect_sum/count
else:
vect_sum = vect_sum
essay_vectorizer_test.append(vect_sum)
top_feats = list(top_2000_features.feature_names.values)
indx = 0
title_vectorizer_train = []
for text in tqdm(preprocessed_titles_train[:45000]):
vect_sum = np.zeros((1,737))
count = 0
for word in tqdm(text.split()):
if word in top_feats:
indx = top_feats.index(word)
count+=1
vect_sum+=model_svd[indx]
if count!=0:
vect_sum = vect_sum/count
else:
vect_sum = vect_sum
title_vectorizer_train.append(vect_sum)
top_feats = list(top_2000_features.feature_names.values)
indx = 0
title_vectorizer_test = []
for text in tqdm(preprocessed_titles_test[:15000]):
vect_sum = np.zeros((1,737))
count = 0
for word in tqdm(text.split()):
if word in top_feats:
indx = top_feats.index(word)
count+=1
vect_sum+=model_svd[indx]
if count!=0:
vect_sum = vect_sum/count
else:
vect_sum = vect_sum
title_vectorizer_test.append(vect_sum)
essay_vectorizer_train_ = []
for i in range(45000):
essay_vectorizer_train_.append(essay_vectorizer_train[i][0])
title_vectorizer_train_ = []
for i in range(45000):
title_vectorizer_train_.append(title_vectorizer_train[i][0])
essay_vectorizer_test_ = []
for i in range(15000):
essay_vectorizer_test_.append(essay_vectorizer_test[i][0])
title_vectorizer_test_ = []
for i in range(15000):
title_vectorizer_test_.append(title_vectorizer_test[i][0])
np.savez_compressed("vectorizer",a = essay_vectorizer_train_,b = title_vectorizer_train_,c = essay_vectorizer_test_,d = title_vectorizer_test_)
data = np.load("vectorizer.npz")
essay_vectorizer_train_ = list(data['a'])
title_vectorizer_train_ = list(data['b'])
essay_vectorizer_test_ = list(data['c'])
title_vectorizer_test_ = list(data['d'])
from scipy.sparse import hstack
from scipy import sparse
# with the same hstack function we are concatinating a sparse matrix and a dense matirx :)
X_tr = hstack((categories_one_hot_train[:45000],sub_categories_one_hot_train[:45000],prefix_one_hot_train[:45000],
project_grade_one_hot_train[:45000],state_one_hot_train[:45000],sparse.csr_matrix(price_standardized_train[:45000]),
sparse.csr_matrix(quantity_standardized_train[:45000]),sparse.csr_matrix(project_standardized_train[:45000]),
sparse.csr_matrix(Essay_count_standardized_train[:45000]),sparse.csr_matrix(title_count_standardized_train[:45000])
,sparse.csr_matrix(essay_pos_train[:45000]),sparse.csr_matrix(essay_neg_train[:45000]),sparse.csr_matrix(essay_neu_train[:45000]),
sparse.csr_matrix(essay_comp_train[:45000]),sparse.csr_matrix(essay_vectorizer_train_),sparse.csr_matrix(title_vectorizer_train_))).tocsr()
X_ts = hstack((categories_one_hot_test[:15000],sub_categories_one_hot_test[:15000],prefix_one_hot_test[:15000],
project_grade_one_hot_test[:15000],state_one_hot_test[:15000],sparse.csr_matrix(price_standardized_test[:15000]),
sparse.csr_matrix(quantity_standardized_test[:15000]),sparse.csr_matrix(project_standardized_test[:15000]),
sparse.csr_matrix(Essay_count_standardized_test[:15000]),sparse.csr_matrix(title_count_standardized_test[:15000])
,sparse.csr_matrix(essay_pos_test[:15000]),sparse.csr_matrix(essay_neg_test[:15000]),sparse.csr_matrix(essay_neu_test[:15000]),
sparse.csr_matrix(essay_comp_test[:15000]),sparse.csr_matrix(essay_vectorizer_test_),sparse.csr_matrix(title_vectorizer_test_))).tocsr()
from xgboost import XGBClassifier
import xgboost as xgb
from sklearn.model_selection import GridSearchCV,RandomizedSearchCV
from sklearn.metrics import roc_auc_score,roc_curve,f1_score,auc
model = XGBoostClassifier(eval_metric = 'auc', num_class = 2, nthread = 4,num_boost_round=5)
parameters = {
#'num_boost_round':[5,10],
'eta':[0.01,0.03,0.05,0.1,0.3],
'gamma':[0.01,0.03,0.1,0.2,0.3],
'max_depth': [1, 5, 10, 50, 100, 500]
}
clf = RandomizedSearchCV(model, param_distributions=parameters,cv = 2,scoring = 'roc_auc',n_jobs=-1)
print("fitting the model")
clf.fit(X_tr, y_train[:45000]["project_is_approved"])
clf.cv_results_
test_auc_5 = clf.cv_results_['mean_test_score']
train_auc_5 = clf.cv_results_['mean_train_score']
model = XGBoostClassifier(eval_metric = 'auc', num_class = 2, nthread = 4,num_boost_round=10)
parameters = {
#'num_boost_round':[5,10],
'eta':[0.01,0.03,0.05,0.1,0.3],
'gamma':[0.01,0.03,0.1,0.2,0.3],
'max_depth': [1, 5, 10, 50, 100, 500]
}
clf = RandomizedSearchCV(model, param_distributions=parameters,cv = 2,scoring = 'roc_auc',n_jobs=-1)
print("fitting the model")
clf.fit(X_tr, y_train[:45000]["project_is_approved"])
clf.cv_results_
test_auc_10 = clf.cv_results_['mean_test_score']
train_auc_10 = clf.cv_results_['mean_train_score']
model = XGBoostClassifier(eval_metric = 'auc', num_class = 2, nthread = 4,num_boost_round=100)
parameters = {
#'num_boost_round':[5,10],
'eta':[0.01,0.03,0.05,0.1,0.3],
'gamma':[0.01,0.03,0.1,0.2,0.3],
'max_depth': [1, 5, 10, 50, 100, 500]
}
clf = RandomizedSearchCV(model, param_distributions=parameters,cv = 2,scoring = 'roc_auc',n_jobs=-1)
print("fitting the model")
clf.fit(X_tr, y_train[:45000]["project_is_approved"])
clf.cv_results_
test_auc_100 = clf.cv_results_['mean_test_score']
train_auc_100 = clf.cv_results_['mean_train_score']
model = XGBoostClassifier(eval_metric = 'auc', num_class = 2, nthread = 4,num_boost_round=250)
parameters = {
#'num_boost_round':[5,10],
'eta':[0.01,0.03,0.05,0.1,0.3],
'gamma':[0.01,0.03,0.1,0.2,0.3],
'max_depth': [1, 5, 10, 50, 100, 500]
}
clf = RandomizedSearchCV(model, param_distributions=parameters,cv = 2,scoring = 'roc_auc',n_jobs=-1)
print("fitting the model")
clf.fit(X_tr, y_train[:45000]["project_is_approved"])
clf.cv_results_
test_auc_250 = clf.cv_results_['mean_test_score']
train_auc_250 = clf.cv_results_['mean_train_score']
model = XGBoostClassifier(eval_metric = 'auc', num_class = 2, nthread = 4,num_boost_round=500)
parameters = {
#'num_boost_round':[5,10],
'eta':[0.01,0.03,0.05,0.1,0.3],
'gamma':[0.01,0.03,0.1,0.2,0.3],
'max_depth': [3, 5, 10, 50, 100, 500]
}
clf = RandomizedSearchCV(model, param_distributions=parameters,cv = 2,scoring = 'roc_auc',n_jobs=-1)
print("fitting the model")
clf.fit(X_tr, y_train[:45000]["project_is_approved"])
clf.cv_results_
test_auc_500 = clf.cv_results_['mean_test_score']
train_auc_500 = clf.cv_results_['mean_train_score']
test_auc = []
for i in [test_auc_5,test_auc_10,test_auc_100,test_auc_250,test_auc_500]:
test_auc.extend(i)
train_auc = []
for i in [train_auc_5,train_auc_10,train_auc_100,train_auc_250,train_auc_500]:
train_auc.extend(i)
depth= pd.Series([1,1,1,1,1,5,5,5,5,5,10,10,10,10,10,50,50,50,50,50,100,100,100,100,100,500,500,500,500,500],index = train_auc)
splits = pd.Series([5,10,100,250,500,5,10,100,250,500,5,10,100,250,500,5,10,100,250,500,5,10,100,250,500,5,10,100,250,500], index = train_auc)
trace = go.Scatter3d(
x=train_auc, y=splits, z=depth,
mode = 'markers+text', showlegend = True,
hovertext = ['AUC_Score','Minimum splits','Depth'],
marker=dict(
symbol = 'cross',
size=8,
color= depth,#'rgba(255,152,75,0.8)',
colorscale='Viridis',
),
line=dict(
color='#1f77b4',
width=1
),
textfont=dict(
family="sans serif",
size=7,
color="LightSeaGreen")
)
import plotly.graph_objects as go
fig = go.Figure(data = [trace])
fig.add_trace(go.Scatter3d(
x=test_auc, y=splits, z=depth,
mode = 'markers+text', showlegend = True,
hovertext = ['AUC_Score','Minimum splits','Depth'],
marker=dict(
size=8,
color= depth,#'rgba(255,152,75,0.8)',
colorscale='Viridis',
),
line=dict(
color='#1f77b4',
width=1
),
textfont=dict(
family="sans serif",
size=7,
color="LightSeaGreen")
))
fig.update_layout(title = "AUC Scores vs Depth and Splits",height = 600,showlegend = False,xaxis = dict(title = 'AUC_SCORE'),
yaxis = dict(title = 'Min_Splits'))
model = XGBoostClassifier(eval_metric = 'auc', num_class = 2, nthread = 4,num_boost_round=5,max_depth = 5,eta = 0.1,gamma = 0.03)
model.fit(X_tr,y_train[:45000]["project_is_approved"])
# batch wise prediction
def proba_predict(model , data):
y_pred_data = []
n_loop = data.shape[0] - data.shape[0]%1000
# here 1000 represents batch_size
for i in range(0,n_loop,1000):
y_pred_data.extend(model.predict_proba(data[i:i+1000])[:,1])
if data.shape[0]%1000!=0:
y_pred_data.extend(model.predict_proba(data[n_loop:])[:,1])
return(y_pred_data)
y_train_pred = proba_predict(model,X_tr)
y_test_pred = proba_predict(model,X_ts)
fpr_train,tpr_train,thres_train = roc_curve(y_train[:45000]["project_is_approved"], y_train_pred)
fpr_test,tpr_test,thres_test = roc_curve(y_test[:15000]["project_is_approved"], y_test_pred)
fig = go.Figure()
fig.add_trace(go.Scatter(x = fpr_train,y = tpr_train,name='Train_AUC',text = "Train AUC Score ="+str(auc(fpr_train, tpr_train))))
fig.add_trace(go.Scatter(x = fpr_test,y = tpr_test,name = "Test_AUC",text = "Test AUC Score ="+str(auc(fpr_test, tpr_test))))
fig.add_trace(go.Scatter(x = np.linspace(0,1,600),y = np.linspace(0,1,600),name = '0.5 AUC Score'))
fig.update_layout(title = 'ROC_AUC SCORE',
xaxis = go.layout.XAxis(title = go.layout.xaxis.Title(text = 'True Positive Rate (TPR)')),
yaxis = go.layout.YAxis(title = go.layout.yaxis.Title(text = "False Positive Rate (FPR)")))
fig.show()
model = XGBoostClassifier(eval_metric = 'auc', num_class = 2, nthread = 4,num_boost_round=10,max_depth = 5,gamma = 0.2,eta = 0.05)
print("Fitting the model")
model.fit(X_tr,y_train[:45000]["project_is_approved"])
y_train_pred = proba_predict(model,X_tr)
y_test_pred = proba_predict(model,X_ts)
fpr_train,tpr_train,thres_train = roc_curve(y_train[:45000]["project_is_approved"], y_train_pred)
fpr_test,tpr_test,thres_test = roc_curve(y_test[:15000]["project_is_approved"], y_test_pred)
fig = go.Figure()
fig.add_trace(go.Scatter(x = fpr_train,y = tpr_train,name='Train_AUC',text = "Train AUC Score ="+str(auc(fpr_train, tpr_train))))
fig.add_trace(go.Scatter(x = fpr_test,y = tpr_test,name = "Test_AUC",text = "Test AUC Score ="+str(auc(fpr_test, tpr_test))))
fig.add_trace(go.Scatter(x = np.linspace(0,1,600),y = np.linspace(0,1,600),name = '0.5 AUC Score'))
fig.update_layout(title = 'ROC_AUC SCORE',
xaxis = go.layout.XAxis(title = go.layout.xaxis.Title(text = 'True Positive Rate (TPR)')),
yaxis = go.layout.YAxis(title = go.layout.yaxis.Title(text = "False Positive Rate (FPR)")))
fig.show()
model = XGBoostClassifier(eval_metric = 'auc', num_class = 2, nthread = 4,num_boost_round=10,max_depth = 3,gamma = 0.2,eta = 0.05)
print("Fitting the model")
model.fit(X_tr,y_train[:45000]["project_is_approved"])
y_train_pred = proba_predict(model,X_tr)
y_test_pred = proba_predict(model,X_ts)
fpr_train,tpr_train,thres_train = roc_curve(y_train[:45000]["project_is_approved"], y_train_pred)
fpr_test,tpr_test,thres_test = roc_curve(y_test[:15000]["project_is_approved"], y_test_pred)
fig = go.Figure()
fig.add_trace(go.Scatter(x = fpr_train,y = tpr_train,name='Train_AUC',text = "Train AUC Score ="+str(auc(fpr_train, tpr_train))))
fig.add_trace(go.Scatter(x = fpr_test,y = tpr_test,name = "Test_AUC",text = "Test AUC Score ="+str(auc(fpr_test, tpr_test))))
fig.add_trace(go.Scatter(x = np.linspace(0,1,600),y = np.linspace(0,1,600),name = '0.5 AUC Score'))
fig.update_layout(title = 'ROC_AUC SCORE',
xaxis = go.layout.XAxis(title = go.layout.xaxis.Title(text = 'True Positive Rate (TPR)')),
yaxis = go.layout.YAxis(title = go.layout.yaxis.Title(text = "False Positive Rate (FPR)")))
fig.show()
model = XGBoostClassifier(eval_metric = 'auc', num_class = 2, nthread = 4,num_boost_round=100,max_depth = 5,gamma = 0.03,eta=0.1)
print("Fitting the model")
model.fit(X_tr,y_train[:45000]["project_is_approved"])
y_train_pred = proba_predict(model,X_tr)
y_test_pred = proba_predict(model,X_ts)
fpr_train,tpr_train,thres_train = roc_curve(y_train[:45000]["project_is_approved"], y_train_pred)
fpr_test,tpr_test,thres_test = roc_curve(y_test[:15000]["project_is_approved"], y_test_pred)
fig = go.Figure()
fig.add_trace(go.Scatter(x = fpr_train,y = tpr_train,name='Train_AUC',text = "Train AUC Score ="+str(auc(fpr_train, tpr_train))))
fig.add_trace(go.Scatter(x = fpr_test,y = tpr_test,name = "Test_AUC",text = "Test AUC Score ="+str(auc(fpr_test, tpr_test))))
fig.add_trace(go.Scatter(x = np.linspace(0,1,600),y = np.linspace(0,1,600),name = '0.5 AUC Score'))
fig.update_layout(title = 'ROC_AUC SCORE',
xaxis = go.layout.XAxis(title = go.layout.xaxis.Title(text = 'True Positive Rate (TPR)')),
yaxis = go.layout.YAxis(title = go.layout.yaxis.Title(text = "False Positive Rate (FPR)")))
fig.show()
model = XGBoostClassifier(eval_metric = 'auc', num_class = 2, nthread = 4,num_boost_round=100,max_depth = 3,gamma = 0.03,eta=0.1)
print("Fitting the model")
model.fit(X_tr,y_train[:45000]["project_is_approved"])
y_train_pred = proba_predict(model,X_tr)
y_test_pred = proba_predict(model,X_ts)
fpr_train,tpr_train,thres_train = roc_curve(y_train[:45000]["project_is_approved"], y_train_pred)
fpr_test,tpr_test,thres_test = roc_curve(y_test[:15000]["project_is_approved"], y_test_pred)
fig = go.Figure()
fig.add_trace(go.Scatter(x = fpr_train,y = tpr_train,name='Train_AUC',text = "Train AUC Score ="+str(auc(fpr_train, tpr_train))))
fig.add_trace(go.Scatter(x = fpr_test,y = tpr_test,name = "Test_AUC",text = "Test AUC Score ="+str(auc(fpr_test, tpr_test))))
fig.add_trace(go.Scatter(x = np.linspace(0,1,600),y = np.linspace(0,1,600),name = '0.5 AUC Score'))
fig.update_layout(title = 'ROC_AUC SCORE',
xaxis = go.layout.XAxis(title = go.layout.xaxis.Title(text = 'True Positive Rate (TPR)')),
yaxis = go.layout.YAxis(title = go.layout.yaxis.Title(text = "False Positive Rate (FPR)")))
fig.show()
model = XGBoostClassifier(eval_metric = 'auc', num_class = 2, nthread = 4,num_boost_round=250,max_depth = 3,gamma = 0.01,eta=0.1)
print("Fitting the model")
model.fit(X_tr,y_train[:45000]["project_is_approved"])
y_train_pred = proba_predict(model,X_tr)
y_test_pred = proba_predict(model,X_ts)
fpr_train,tpr_train,thres_train = roc_curve(y_train[:45000]["project_is_approved"], y_train_pred)
fpr_test,tpr_test,thres_test = roc_curve(y_test[:15000]["project_is_approved"], y_test_pred)
fig = go.Figure()
fig.add_trace(go.Scatter(x = fpr_train,y = tpr_train,name='Train_AUC',text = "Train AUC Score ="+str(auc(fpr_train, tpr_train))))
fig.add_trace(go.Scatter(x = fpr_test,y = tpr_test,name = "Test_AUC",text = "Test AUC Score ="+str(auc(fpr_test, tpr_test))))
fig.add_trace(go.Scatter(x = np.linspace(0,1,600),y = np.linspace(0,1,600),name = '0.5 AUC Score'))
fig.update_layout(title = 'ROC_AUC SCORE',
xaxis = go.layout.XAxis(title = go.layout.xaxis.Title(text = 'True Positive Rate (TPR)')),
yaxis = go.layout.YAxis(title = go.layout.yaxis.Title(text = "False Positive Rate (FPR)")))
fig.show()
model = XGBoostClassifier(eval_metric = 'auc', num_class = 2, nthread = 4,num_boost_round=500,max_depth = 3,gamma = 0.1,eta = 0.03)
print("Fitting the model")
model.fit(X_tr,y_train[:45000]["project_is_approved"])
y_train_pred = proba_predict(model,X_tr)
y_test_pred = proba_predict(model,X_ts)
fpr_train,tpr_train,thres_train = roc_curve(y_train[:45000]["project_is_approved"], y_train_pred)
fpr_test,tpr_test,thres_test = roc_curve(y_test[:15000]["project_is_approved"], y_test_pred)
fig = go.Figure()
fig.add_trace(go.Scatter(x = fpr_train,y = tpr_train,name='Train_AUC',text = "Train AUC Score ="+str(auc(fpr_train, tpr_train))))
fig.add_trace(go.Scatter(x = fpr_test,y = tpr_test,name = "Test_AUC",text = "Test AUC Score ="+str(auc(fpr_test, tpr_test))))
fig.add_trace(go.Scatter(x = np.linspace(0,1,600),y = np.linspace(0,1,600),name = '0.5 AUC Score'))
fig.update_layout(title = 'ROC_AUC SCORE',
xaxis = go.layout.XAxis(title = go.layout.xaxis.Title(text = 'True Positive Rate (TPR)')),
yaxis = go.layout.YAxis(title = go.layout.yaxis.Title(text = "False Positive Rate (FPR)")))
fig.show()
from prettytable import PrettyTable
#If you get a ModuleNotFoundError error , install prettytable using: pip3 install prettytable
x = PrettyTable()
x.field_names = ["Model", "Max_Depth","Min_Number_split","Eta","lambda","BEST_AUC_SCORE"]
x.add_row(["TruncatedSVD",5 ,5,0.03,0.1,0.6240])
x.add_row(["TruncatedSVD",5 ,10,0.05,0.2,0.6290])
x.add_row(["TruncatedSVD",3 ,10,0.05,0.2,0.6323])
x.add_row(["TruncatedSVD",5 ,100,0.03,0.1,0.6182])
x.add_row(["TruncatedSVD",3 ,100,0.03,0.1,0.6391])
x.add_row(["TruncatedSVD",3 ,250,0.01,0.1,0.6244])
x.add_row(["TruncatedSVD",3 ,500,0.03,0.1,0.6398])
print(x)